<template>
    <span>{{number}}</span>
</template>

<script>
import {reactive,toRefs,onMounted,onBeforeUnmount} from 'vue'
import {useRouter} from 'vue-router'
export default {
    props:['time','backTo'],
    setup(props,context) {
        const router = useRouter()

        const state = reactive({
            number:props.time || 60,
            backTo:props.backTo,
            doFlag:true,
            st:''
        })

        onMounted(() =>{
            countDown()
        })
        
        const countDown = ()=>{
            if(!state.doFlag) return

            if(state.number>0){   
              state.st = setTimeout(()=>{
                  state.number--
                  countDown()
              },1000)
            }else{
                context.emit('over')
               //state.backTo && router.push(state.backTo)
            }
        }

        onBeforeUnmount(()=>{  // 销毁组件
            stopCountDown()
        })

        const startCountDown = ()=>{ // 开始倒计时
            clearTimeout(state.st)
            state.doFlag = true
            console.log("开始倒计时....")
            countDown()
        }

        const stopCountDown =() =>{ // 停止倒计时
            clearTimeout(state.st)
            state.doFlag = false
            state.number = props.time || 60
            console.log("倒计时关闭了")
        }
        
        return {
            ...toRefs(state),
            stopCountDown,
            startCountDown
        }
    },
}
</script>